<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Cache;

class Customer extends BaseController
{
    /**
     * 保存/更新客户实名信息
     */
    public function saveCustomerInfo()
    {
        $memberId = $this->getMemberIdFromToken();

        if (!$memberId) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        $customerName = $this->request->param('customer_name', '');
        $customerCard = $this->request->param('customer_card', '');
        $customerPhone = $this->request->param('customer_phone', '');
        $customerSex = $this->request->param('customer_sex', '');
        $customerAge = $this->request->param('customer_age', '');
        $customerAddress = $this->request->param('customer_address', '');

        if (empty($customerName) || empty($customerCard) || empty($customerPhone)) {
            return json(['code' => 400, 'msg' => '姓名、身份证号、手机号不能为空']);
        }

        // 验证身份证号格式
        if (!$this->validateIdCard($customerCard)) {
            return json(['code' => 400, 'msg' => '身份证号格式不正确']);
        }

        // 验证手机号格式
        if (!$this->validatePhone($customerPhone)) {
            return json(['code' => 400, 'msg' => '手机号格式不正确']);
        }

        try {
            // 检查是否已存在该会员的客户信息
            $existCustomer = Db::name('customerinfo')
                ->where('member_id', $memberId)
                ->find();

            $customerData = [
                'CustomerName' => $customerName,
                'CustomerCard' => $customerCard,
                'CustomerPhone' => $customerPhone,
                'CustomerSex' => $customerSex,
                'CustomerDateofBirth' => substr($customerCard, 6, 4) . '-' . substr($customerCard, 10, 2) . '-' . substr($customerCard, 12, 2) . ' 00:00:00',
                'CustomerAge' => $customerAge,
                'CustomerAdress' => $customerAddress,
                'member_id' => $memberId
            ];

            if ($existCustomer) {
                // 更新现有客户信息
                $result = Db::name('customerinfo')
                    ->where('member_id', $memberId)
                    ->update($customerData);

                if ($result !== false) {
                    $customerData['ID'] = $existCustomer['ID'];
                    return json([
                        'code' => 200,
                        'data' => $customerData,
                        'msg' => '客户信息更新成功'
                    ]);
                } else {
                    return json(['code' => 500, 'msg' => '客户信息更新失败']);
                }
            } else {
                // 新增客户信息
                $customerData['CreateDate'] = date('Y-m-d H:i:s');
                $customerId = Db::name('customerinfo')->insertGetId($customerData);

                if ($customerId) {
                    $customerData['ID'] = $customerId;
                    return json([
                        'code' => 200,
                        'data' => $customerData,
                        'msg' => '客户信息保存成功'
                    ]);
                } else {
                    return json(['code' => 500, 'msg' => '客户信息保存失败']);
                }
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }

    /**
     * 获取客户信息
     */
    public function getCustomerInfo()
    {
        $memberId = $this->getMemberIdFromToken();

        if (!$memberId) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        try {
            $customerInfo = Db::name('customerinfo')
                ->where('member_id', $memberId)
                ->find();

            if ($customerInfo) {
                return json([
                    'code' => 200,
                    'data' => $customerInfo,
                    'msg' => '获取成功'
                ]);
            } else {
                return json([
                    'code' => 404,
                    'data' => null,
                    'msg' => '暂无客户信息'
                ]);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }

    /**
     * 根据身份证号查询客户信息
     */
    public function getCustomerByIdCard()
    {
        $customerCard = $this->request->param('customer_card', '');

        if (empty($customerCard)) {
            return json(['code' => 400, 'msg' => '身份证号不能为空']);
        }

        try {
            $customerInfo = Db::name('customerinfo')
                ->where('CustomerCard', $customerCard)
                ->find();

            if ($customerInfo) {
                return json([
                    'code' => 200,
                    'data' => $customerInfo,
                    'msg' => '获取成功'
                ]);
            } else {
                return json([
                    'code' => 404,
                    'data' => null,
                    'msg' => '客户信息不存在'
                ]);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }

    /**
     * 验证客户实名信息
     */
    public function verifyCustomerInfo()
    {
        $memberId = $this->getMemberIdFromToken();

        if (!$memberId) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        try {
            $customerInfo = Db::name('customerinfo')
                ->where('member_id', $memberId)
                ->find();

            if ($customerInfo) {
                // 检查必要字段是否完整
                $requiredFields = ['CustomerName', 'CustomerCard', 'CustomerPhone'];
                $isComplete = true;

                foreach ($requiredFields as $field) {
                    if (empty($customerInfo[$field])) {
                        $isComplete = false;
                        break;
                    }
                }

                return json([
                    'code' => 200,
                    'data' => [
                        'is_verified' => $isComplete,
                        'customer_info' => $customerInfo
                    ],
                    'msg' => $isComplete ? '实名信息已完整' : '实名信息不完整'
                ]);
            } else {
                return json([
                    'code' => 200,
                    'data' => [
                        'is_verified' => false,
                        'customer_info' => null
                    ],
                    'msg' => '暂未填写实名信息'
                ]);
            }
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '系统错误：' . $e->getMessage()]);
        }
    }

    /**
     * 上传客户图片
     */
    public function uploadCustomerImage()
    {
        $memberId = $this->getMemberIdFromToken();

        if (!$memberId) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        $file = $this->request->file('image');

        if (!$file) {
            return json(['code' => 400, 'msg' => '请选择图片文件']);
        }

        try {
            // 验证文件类型
            $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
            $fileExt = strtolower($file->getOriginalExtension());

            if (!in_array($fileExt, $allowedTypes)) {
                return json(['code' => 400, 'msg' => '只允许上传jpg、jpeg、png、gif格式的图片']);
            }

            // 生成文件名
            $fileName = 'customer_' . $memberId . '_' . date('YmdHis') . '.' . $fileExt;

            // 保存文件
            $savePath = 'static/customer_images/';
            $file->move(public_path() . $savePath, $fileName);

            $imageUrl = '/' . $savePath . $fileName;

            // 更新客户信息中的图片字段
            Db::name('customerinfo')
                ->where('member_id', $memberId)
                ->update(['CustomerImages' => $imageUrl]);

            return json([
                'code' => 200,
                'data' => [
                    'image_url' => $imageUrl
                ],
                'msg' => '图片上传成功'
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '图片上传失败：' . $e->getMessage()]);
        }
    }

    /**
     * 从token获取会员ID
     */
    private function getMemberIdFromToken()
    {
        $token = $this->request->header('token', '');

        if (empty($token)) {
            return false;
        }

        return Cache::get('member_token_' . $token);
    }

    /**
     * 验证身份证号
     */
    private function validateIdCard($idCard)
    {
        // 简单的身份证号验证（18位）
        if (strlen($idCard) != 18) {
            return false;
        }

        return preg_match('/^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/', $idCard);
    }

    /**
     * 验证手机号
     */
    private function validatePhone($phone)
    {
        return preg_match('/^1[3-9]\d{9}$/', $phone);
    }
}
